package com.fateai.module.swipeItemHelper;

import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

public class SwipeMenuHelper<T extends SwipeMenuHelper.SwipeViewHolder> {

    private final ItemTouchHelper itemTouchHelper;
    private final SwipeCallback swipeCallback;
    private final RecyclerView recyclerView;

    public SwipeMenuHelper(RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
        this.swipeCallback = new SwipeCallback();
        this.itemTouchHelper = new ItemTouchHelper(swipeCallback);
        attachToRecyclerView();
    }

    private void attachToRecyclerView() {
        itemTouchHelper.attachToRecyclerView(recyclerView);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    closeMenu();
                }
            }
        });

        recyclerView.addOnItemTouchListener(new RecyclerView.SimpleOnItemTouchListener() {
            @Override
            public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
                if (e.getAction() == MotionEvent.ACTION_DOWN) {
                    if (swipeCallback.isMenuOpen()) {
                        T openHolder = swipeCallback.getSwipedViewHolder();
                        if (openHolder != null) {
                            // 检查点击是否在菜单区域内
                            View menuView = openHolder.menuView;
                            int[] location = new int[2];
                            menuView.getLocationOnScreen(location);

                            Rect menuRect = new Rect(
                                    location[0],
                                    location[1],
                                    location[0] + menuView.getWidth(),
                                    location[1] + menuView.getHeight()
                            );

                            // 转换为屏幕坐标
                            int screenX = (int) (e.getRawX());
                            int screenY = (int) (e.getRawY());

                            if (menuRect.contains(screenX, screenY)) {
                                // 点击在菜单区域内 - 不关闭菜单
                                return false;
                            } else {
                                // 点击在菜单区域外 - 关闭菜单
                                closeMenu();
                                return true;
                            }
                        }
                    }
                }
                return false;
            }
        });
    }

    public void closeMenu() {
        swipeCallback.closeMenu();
    }

    public boolean isMenuOpen() {
        return swipeCallback.isMenuOpen();
    }

    // 高级配置方法
    public void setSwipeSensitivity(float sensitivity) {
        if (sensitivity < 0.1f || sensitivity > 2.0f) {
            throw new IllegalArgumentException("Sensitivity must be between 0.1 and 2.0");
        }
        swipeCallback.setSwipeSensitivity(sensitivity);
    }

    public void setSwipeDirection(int direction) {
        if (direction != ItemTouchHelper.LEFT &&
                direction != ItemTouchHelper.RIGHT &&
                direction != (ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT)) {
            throw new IllegalArgumentException("Invalid swipe direction");
        }
        swipeCallback.setSwipeDirection(direction);
    }

    public static abstract class SwipeViewHolder extends RecyclerView.ViewHolder {
        public final View contentView;
        public final View menuView;

        public SwipeViewHolder(@NonNull View itemView, @IdRes int contentViewId, @IdRes int menuViewId) {
            super(itemView);
            contentView = itemView.findViewById(contentViewId);
            menuView = itemView.findViewById(menuViewId);

            if (contentView == null || menuView == null) {
                throw new IllegalArgumentException("布局必须包含content_layout和menu_layout");
            }

            // 初始隐藏菜单
            menuView.setVisibility(View.INVISIBLE);
        }
        // 提供菜单视图的访问方法
        public View getMenuView() {
            return menuView;
        }
    }

    private class SwipeCallback extends ItemTouchHelper.Callback {

        private static final float SWIPE_THRESHOLD = 0.5f;
        private static final float SWIPE_VELOCITY_THRESHOLD = 2000;

        private float sensitivity = 1.0f; // 默认灵敏度
        private int swipeDirection = ItemTouchHelper.LEFT;
        private T swipedViewHolder;
        private float menuWidth = -1;

        public void setSwipeDirection(int direction) {
            this.swipeDirection = direction;
        }

        public void setSwipeSensitivity(float sensitivity) {
            this.sensitivity = sensitivity;
        }

        @Override
        public int getMovementFlags(@NonNull RecyclerView recyclerView,
                                    @NonNull RecyclerView.ViewHolder viewHolder) {
            return makeMovementFlags(0, swipeDirection);
        }

        @Override
        public boolean onMove(@NonNull RecyclerView recyclerView,
                              @NonNull RecyclerView.ViewHolder viewHolder,
                              @NonNull RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
            // 空实现
        }

        @SuppressWarnings("unchecked")
        @Override
        public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
            super.onSelectedChanged(viewHolder, actionState);

            // 滑动开始时测量菜单宽度
            if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE &&
                    viewHolder instanceof SwipeViewHolder) {

                T holder = (T) viewHolder;
                if (menuWidth < 0) {
                    holder.menuView.setVisibility(View.VISIBLE);
                    holder.menuView.measure(
                            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                            View.MeasureSpec.makeMeasureSpec(holder.itemView.getHeight(), View.MeasureSpec.EXACTLY)
                    );
                    menuWidth = holder.menuView.getMeasuredWidth();
                    holder.menuView.setVisibility(View.INVISIBLE);
                }
            }
        }

        @SuppressWarnings("unchecked")
        @Override
        public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView,
                                @NonNull RecyclerView.ViewHolder viewHolder,
                                float dX, float dY, int actionState, boolean isCurrentlyActive) {

            if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE &&
                    viewHolder instanceof SwipeViewHolder) {

                T holder = (T) viewHolder;

                // 限制滑动范围
                float translationX = Math.max(dX, -menuWidth);

                // 移动内容视图
                holder.contentView.setTranslationX(translationX);

                // 控制菜单显示
                if (Math.abs(translationX) > 5) {
                    holder.menuView.setVisibility(View.VISIBLE);

                    // 设置菜单位置（跟随内容视图）
                    holder.menuView.setTranslationX(translationX + holder.contentView.getWidth());
                } else {
                    holder.menuView.setVisibility(View.INVISIBLE);
                }

                // 更新状态
                if (dX == 0) {
                    if (swipedViewHolder == holder) {
                        swipedViewHolder = null;
                    }
                } else {
                    if (swipedViewHolder != null && swipedViewHolder != holder) {
                        closeMenu();
                    }
                    swipedViewHolder = holder;
                }
            } else {
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            }
        }

        @Override
        public float getSwipeThreshold(@NonNull RecyclerView.ViewHolder viewHolder) {
            // 阈值与灵敏度成反比
            return SWIPE_THRESHOLD / sensitivity;
        }

        @Override
        public float getSwipeEscapeVelocity(float defaultValue) {
            // 逃逸速度与灵敏度成正比
            return SWIPE_VELOCITY_THRESHOLD * sensitivity;
        }

        @SuppressWarnings("unchecked")
        @Override
        public void clearView(@NonNull RecyclerView recyclerView,
                              @NonNull RecyclerView.ViewHolder viewHolder) {
            super.clearView(recyclerView, viewHolder);

            if (viewHolder instanceof SwipeViewHolder) {
                T holder = (T) viewHolder;
                resetViewHolder(holder);

                if (swipedViewHolder == holder) {
                    swipedViewHolder = null;
                }
            }
        }

        private void resetViewHolder(T viewHolder) {
            viewHolder.contentView.setTranslationX(0);
            viewHolder.menuView.setVisibility(View.INVISIBLE);
            viewHolder.menuView.setTranslationX(0);
        }

        public void closeMenu() {
            if (swipedViewHolder != null) {
                resetViewHolder(swipedViewHolder);
                swipedViewHolder = null;
            }
        }

        public boolean isMenuOpen() {
            return swipedViewHolder != null;
        }

        public T getSwipedViewHolder(){
            return swipedViewHolder;
        }
    }
}

